﻿namespace Devonline.AspNetCore;

/// <summary>
/// Http 拦截器
/// </summary>
public class HttpInterceptor
{
    /// <summary>
    /// 拦截器全局唯一对象
    /// </summary>
    private static HttpInterceptor _instance = new();
    /// <summary>
    /// 拦截器全局唯一对象访问方式
    /// </summary>
    public static HttpInterceptor Instance => _instance;

    /// <summary>
    /// 按关键词拦截集合
    /// 键值分别为拦截的业务名称和业务描述
    /// 全局拦截请: HTTP_REQUEST_INTERCEPT_GLOBAL=全局业务
    /// </summary>
    private static Dictionary<string, string> _interceptors = [];
    /// <summary>
    /// 拦截是否激活中
    /// </summary>
    public string? this[string key] => _interceptors.GetValue(key);

    /// <summary>
    /// 激活全局拦截
    /// </summary>
    public void Activate() => Activate(HTTP_REQUEST_INTERCEPT_GLOBAL, "全局业务");
    /// <summary>
    /// 激活关键词拦截
    /// </summary>
    /// <param name="key">关键词</param>
    /// <param name="desc">业务描述</param>
    /// <exception cref="ArgumentNullException"></exception>
    public void Activate(string key, string desc)
    {
        if (string.IsNullOrWhiteSpace(key))
        {
            throw new ArgumentNullException(nameof(key), "关键词不能为空!");
        }

        _interceptors.SetValue(key, desc);
    }
    /// <summary>
    /// 完成全局拦截任务, 即取消全局拦截
    /// </summary>
    public bool Done() => Done(HTTP_REQUEST_INTERCEPT_GLOBAL);
    /// <summary>
    /// 完成关键词拦截任务, 即取消关键词拦截, 移除关键词拦截
    /// </summary>
    /// <param name="key">关键词</param>
    /// <exception cref="ArgumentNullException"></exception>
    public bool Done(string key)
    {
        if (string.IsNullOrWhiteSpace(key))
        {
            throw new ArgumentNullException(nameof(key), "关键词不能为空!");
        }

        lock (_interceptors)
        {
            return _interceptors.Remove(key);
        }
    }
}